package javaweb_work01.classesContrl.Servlet;

import javaweb_work01.classesContrl.Entity.Classes;
import javaweb_work01.classesContrl.Service.CountClassesService;
import javaweb_work01.classesContrl.Service.ShowClassesService;
import javaweb_work01.classesContrl.Service.StudentsSumService;
import javaweb_work01.main.Entity.Students;
import javaweb_work01.main.Service.CountService;
import javaweb_work01.main.Service.ShowService;
import javaweb_work01.main.Utils.PageContrl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ShowClassesServlet", urlPatterns = "/showClasses")
public class ShowClassesServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到主页面分页按钮设置的start属性值，即每一页的第一条数据的编号
        int start = Integer.parseInt(request.getParameter("start"));
        //得到班级总数
        CountClassesService countClassesService = new CountClassesService();
        int count = countClassesService.countClassesService();
        //用得到的班级总数和start的属性值构造新的PageContrl对象
        PageContrl pageContrl = new PageContrl(start,5,count);
        //将新构造的PageContrl对象作为参数传入Service,调用Dao层方法,得到该页的班级数据集合
        ShowClassesService showClassesService = new ShowClassesService();
        List<Classes> classes = showClassesService.showClassesService(pageContrl);

        //得到每个班的人数
        StudentsSumService studentsSumService = new StudentsSumService();
        //声明一个Classes集合用于记录添加班级人数后的Classes对象
        for(Classes cs:classes){
            int i = studentsSumService.studentsSumService(cs.getCid());
            cs.setSum(i);
        }

        //将得到的PageContrl对象和Classes对象放入session中实现共享
        request.getSession().setAttribute("classesPageContrl",pageContrl);
        request.getSession().setAttribute("showClasses",classes);
        //跳转到班级管理页面
        response.sendRedirect("classes.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
